/*
 StateListViewController.m
 LegislatorLookup
 
 This controller is responsible for displaying the Search View
 which displays a list of states and or candidates (after a search)
 
 Copyright (c) 2009 Nabil Ahmad
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the 
 documentation and/or other materials provided with the distribution. 
 
 3. The name of the author may not be used to endorse or promote products
 derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/	

#import "StateListViewController.h"
#import "LegislatorListViewController.h"
#import "LegislatorViewController.h"
#import "WebServiceController.h"
#import "Legislator.h"

#define CELL_TYPE_LEGISLATOR @"LEG"
#define CELL_TYPE_STATE @"STATE"
#define NO_RESULTS_TEXT @"No results found"

@implementation StateListViewController

- (void) loadView 
{
	[super loadView];
	self.title = @"Search";		//set title of page

	// Add search bar
    searchBar = [[UISearchBar alloc] initWithFrame:self.tableView.bounds];
    [searchBar sizeToFit]; // Get the default height for a search bar.
    searchBar.delegate = self;
	searchBar.showsCancelButton = YES;
	searchBar.placeholder = @"Search for a Legislator or State";
	self.tableView.tableHeaderView = searchBar;
	
	// Register for Keyboard notifications 
	[self registerForKeyboardNotifications];
	keyboardIsOpen = NO;
	
	// Load states list from property list file
	NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];
	stateAbbvMap = [[NSDictionary dictionaryWithContentsOfFile:plistPath] retain];
	
	// Create a sorted array containing only state names
	states = [[NSMutableArray alloc] init];
	[states setArray:[stateAbbvMap allKeys]];
	[states sortUsingSelector:@selector(caseInsensitiveCompare: )];	
	
	// Create a copy that can be manipulated
	searchResults = [states mutableCopy];
}

- (void) locate
{
	NSLog(@"tapped locate");
}

- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning]; 
}

// Allows controller to recieve notifications for keyboard state
- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

// Only one section (results)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}


// Return number of states/search results
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return searchResults.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSString *value = [searchResults objectAtIndex:indexPath.row];
	
	// Display candidates differently than states
	if ([value rangeOfString:@","].length > 0) 
	{
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_TYPE_LEGISLATOR];
		
		if (cell == nil) 
		{
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CELL_TYPE_LEGISLATOR] autorelease];
		}
		
		cell.text = value;		
		cell.image = [[legislators objectForKey:cell.text] partyIcon];
		
		return cell;
	}
	// Display states
	else 
	{
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_TYPE_STATE];
		
		if (cell == nil) 
		{
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CELL_TYPE_STATE] autorelease];
		}
		
		cell.text = value;
		
		return cell;
	}
}

// Take action on row selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	
	// If keyboard is open, then tap should just hide keyboard
	if (keyboardIsOpen)
	{
		[searchBar resignFirstResponder];
	}
	// otherwise go to appropriate page
	else 
	{
		NSString *key = [searchResults objectAtIndex:indexPath.row];

		// if text contains a ',' it is a legislator name in which case we go directly to the 
		// legislator details
		if ([key rangeOfString:@","].length > 0)
		{
			LegislatorViewController *legislatorViewController = [[LegislatorViewController alloc] initWithLegislator:[legislators objectForKey:key]];
			
			[self.navigationController pushViewController:legislatorViewController animated:YES];
			[legislatorViewController release];
		} 
		// Otherwise (unless it's 'no results') go to list of reps for state
		else if ([key rangeOfString:NO_RESULTS_TEXT].length == 0) 
		{
			// Lookup the abbreviated state name and pass to controller
			NSString *stateAbbv = [stateAbbvMap objectForKey:key];
			LegislatorListViewController *legislatorListViewController = [[LegislatorListViewController alloc] initWithState:stateAbbv];
			legislatorListViewController.title = [searchResults objectAtIndex:indexPath.row];
			
			[self.navigationController pushViewController:legislatorListViewController animated:YES];
			[legislatorListViewController release];
		}
	}
}

// Show appropriate indicator
- (UITableViewCellAccessoryType)tableView:(UITableView *)table accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath 
{
	NSString *key = [searchResults objectAtIndex:indexPath.row];
	
	if ([key rangeOfString:NO_RESULTS_TEXT].length == 0)
		return UITableViewCellAccessoryDisclosureIndicator;
	else
		return UITableViewCellAccessoryNone;
}

/** SEARCH BAR METHODS **/

// Use cancel button to clear search results
- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar
{
	if ([aSearchBar.text length] == 0)
	{
		aSearchBar.text = @"";
		searchResults = [states mutableCopy];
	}

	[aSearchBar endEditing:YES];

	[self.tableView reloadData];
}
 
// Toggle keyboard on
- (void)keyboardWasShown:(NSNotification*)aNotification
{
	keyboardIsOpen = YES;
}

// Toggle keyboard off
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
	keyboardIsOpen = NO;
}

// Perform Search
- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar
{
    // Stop editing and hide the keyboard
    [aSearchBar endEditing:YES];
    
    // Re-filter the array of names
    [searchResults removeAllObjects];
	
    NSString *query = aSearchBar.text;
    for (NSString *name in states) {
        // Start by assuming that the name matches.
        BOOL doesNameMatch = YES;
        // Only search if we have a non-zero length query string
        if (query.length > 0) {
            NSRange range = [name rangeOfString:query options:NSCaseInsensitiveSearch];
            doesNameMatch = (range.length > 0);
        }
        if (doesNameMatch) {
            [searchResults addObject:name];
        }
    }
    
	// Search for legislators meeting search criteria
	legislators = [[WebServiceController getLegislatorsSearch:aSearchBar.text] retain];
	
	// Add all legislator names
	[searchResults addObjectsFromArray:[legislators allKeys]];
		
    // Add a placeholder if we ended up with no results
    if (searchResults.count == 0) {
        [searchResults addObject:NO_RESULTS_TEXT];
    }
    
    [self.tableView reloadData];
}

// Deallocate all objects
- (void)dealloc {
    [super dealloc];
	
    if (searchBar.delegate == self) {
        searchBar.delegate = nil;
    }
	
	[states release];
	[legislators release];
	[searchResults release];
    [searchBar release];
}


@end

